

// import CryptoJS from 'crypto-js';
import * as CryptoJS from 'crypto-js';

/**
* 非空验证
* @param {string} strings
*/
export const isNull = (strings: string) => {
  if (!strings) {
    return true;
  }
  if (strings.replace(/(^\s*)|(\s*$)/g, '').length === 0) {
    return true;
  }
  return false;

};

/**
* 存localStorage
* @param {string} name key
* @param {*} name value
*/
export const setLocal = (name: string, value: any) => {
  window.localStorage.setItem(name, JSON.stringify(value));
};

/**
* 取localStorage
* @param {string} name key
*/
export const getLocal = (name: any) => {
  const names: any = window.localStorage.getItem(name);
  return JSON.parse(names);
};


/**
* 存sessionStorage
* @param {string} name key
* @param {*} name value
*/
export const setSession = (name: string, value: any) => {
  window.sessionStorage.setItem(name, JSON.stringify(value));
};


/**
* 取sessionStorage
* @param {string} name key
*/
export const getSession = (name: string) => {
  const names: any = window.sessionStorage.getItem(name);
  return JSON.parse(names);
};

/**
* 数字验证
* @param {string} num 数字
*/
export const numVerification = (num: any) => {
  const numCodeVerification = /^[0-9]*$/;
  return numCodeVerification.test(num);
};

/**
* 数字验证  允许为空
* @param {string} num 数字
*/
export const numVerificationTwo = (num: any) => {
  if (!num) {
    return true;
  }
  const numCodeVerification = /^[0-9]*$/;
  return numCodeVerification.test(num);
};

/**
* 手机号验证
* @param {string} phone 手机号
*/
export const codeVerification = (phone: any) => {
  const phoneCodeVerification = /^1[3-9]\d{9}$/;
  return phoneCodeVerification.test(phone);
};

/**
* 手机号+座机 验证 座机号不带-
* @param {string} phone 手机号+座机号
*/
export const phoneAll1 = (number: any) => {
  const phoneVerify = /^((0\d{2,3}-\d{8,9})|(0\d{2,3}\d{7,8})|(1[3-9]\d{9}))$/;
  return phoneVerify.test(number);
};

/**
* 手机号+座机 验证 010-88888888  可以带-
* @param {string} phone 手机号+座机号
*/
export const phoneAll = (number: any) => {
  const phoneVerify = /^((0\d{2,3}-\d{8,9})|(0\d{2,3}\d{7,8})|(1[3-9]\d{9})|(\d{7,8}))$/;
  // let phoneVerify = /^((0?\d{2,3}\-)?[1-9]\d{6,7}(\-\d{1,4})|(0\d{2,3}\d{7,8})|(1[3-9]\d{9}|(\d{7,8})))?$/
  return phoneVerify.test(number);
};

// 校验邮箱
export const email = (str: any) => {
  const reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
  return reg.test(str);
};


/**
 *
 * @param {string} socialCode   校验统一社会代码
 * @returns
 */
export const socialCode = (str: string) => {
  const reg = /[^_IOZSVa-z\W]{2}\d{6}[^_IOZSVa-z\W]{10}$/g;
  return reg.test(str);
};


/**
 * 验证统一社会信用代码
 * @param { string } code 统一社会信用代码
 * @returns {
 *   isPass, // 验证是否通过，默认通过，为true，否则为false
 *   errorMessage, // 错误信息，isPass为true则为''
 * }
 * */
export function checkSocialCreditCode(code: any) {
  let isPass = true; // 是否验证通过，默认通过，为true
  let errorMessage = ''; // 错误信息
  const reg = /^\w\w\d{6}\w{9}\w$/; // 18位及正则校验

  // 空值直接返回false
  if (!code) {
    isPass = false;
    errorMessage = '请输入所属企业的社会统一信用代码！';
  } else if (code.length !== 18 || !reg.test(code)) {
    isPass = false;
    errorMessage = '不是有效的统一社会信用代码！';
  } else {
    const codeOrigin = '0123456789ABCDEFGHJKLMNPQRTUWXY'; // 统一社会信用代码可用字符 不含I、O、S、V、Z
    const weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28]; // 统一社会信用代码相对应顺序的加权因子

    let ci; // 统一社会信用代码相应顺序的值
    let wi; // 统一社会信用代码相应顺序的加权因子
    let total = 0; // 计算结果

    // 数值与加权因子相乘之和
    for (let i = 0; i < code.length - 1; i++) {
      ci = codeOrigin.indexOf(code[i]);
      wi = weightedfactors[i];
      total += ci * wi;
    }

    // 最后一位校验
    let logicCheckCode: any = 31 - total % 31;
    if (logicCheckCode === 31) {
      logicCheckCode = 0;
    }
    logicCheckCode = codeOrigin[logicCheckCode];
    if (logicCheckCode !== code.slice(17)) {
      isPass = false;
      errorMessage = '不是有效的统一社会信用代码！';
    }
  }

  return {
    isPass,
    errorMessage,
  };
}


// /**
// * 数字验证
// * @param {string} num 可以为空的数字校验
// */
// export const numVerificationOrNo = (num) => {
//   let numCodeVerification = /^[0-9]*$/;
//   if (num) {
//     return numCodeVerification.test(num);
//   } else {
//     return true
//   }
//   // return numCodeVerification.test(num);
// }


/**
 *
 * @param {string} idcrad  校验身份证号
 * @returns
 */
export const idCard = (str: string) => {
  const reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
  return reg.test(str);
};

/**
* 密码校验
* @param {string} phone 密码由大小写英文,数字,特殊字符组成
*/
// export const passwordVerification = (val) => {
//   let phoneCodeVerification = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])).*$/;

//   return phoneCodeVerification.test(val);
// }
// /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/
/**
* 密码校验
* @param {string} phone 密码由大小写英文,数字组成
*/
export const passwordVerification = (val: string) => {
  const phoneCodeVerification = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/;

  return phoneCodeVerification.test(val);
};


//获取当前年月日时分
export const curentTimeLogin = () => {
  const now = new Date(); const year = String(now.getFullYear()); //年
  const month = now.getMonth() + 1; //月
  const day = now.getDate(); //日

  const hh = now.getHours(); //时
  const mm = now.getMinutes(); //分

  let clock = year; if (month < 10) {
    clock += '0';
  }

  clock += month; if (day < 10) {
    clock += '0';
  }

  clock += day; if (hh < 10) {
    clock += '0';
  }

  clock += hh; if (mm < 10) {
    clock += '0';
  }
  clock += mm;
  return clock;
};

//输出aes秘钥 秘钥规则是密码+当前日期时分 使用 sha256加密取16位  密码默认取localStorage里面存储的密码 登录页面取输入的密码
export const fromCharCode = () => {
  //年月日时分,分取整数
  // var str = password + curentTime().slice(0, curentTime().length - 4);
  let str = curentTimeLogin().slice(0, curentTimeLogin().length - 4); //更改后不需要密码 str="20210531"
  const sha256 = require('js-sha256').sha256;//这里用的是require方法
  str = sha256(str).slice(0, 16);//要加密的秘钥
  return str;
};

/**
* aes加密
* @param {string} word 需要加密的字符串
* @param {string} secretKey 加密规则秘钥
*/
export const encrypt = (word: string, secretKey = fromCharCode()) => { //
  const key = CryptoJS.enc.Utf8.parse(secretKey);
  const iv = CryptoJS.enc.Utf8.parse(secretKey);
  const srcs = CryptoJS.enc.Utf8.parse(word);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
};

/**
* aes解密
* @param {string} word 需要解密的字符串
* @param {string} secretKey 解密规则秘钥
*/
export const decrypt = (word: string, keyStr = fromCharCode()) => { //
  const key = CryptoJS.enc.Utf8.parse(keyStr);
  const iv = CryptoJS.enc.Utf8.parse(keyStr);
  const decrypt = CryptoJS.AES.decrypt(word, key, { iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
};


/**
* 随机生成密码(至少包含一个大写字母，小写字母，数字，特殊符号)
* @param {number} length 密码长度
*/
export const randomPassword = (length: number) => {
  length = Number(length);
  // Limit length
  if (length < 6) {
    length = 6;
  } else if (length > 16) {
    length = 16;
  }
  const passwordArray = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz', '1234567890', '!@#$%&*()'];
  const password = [];
  let n = 0;
  for (let i = 0; i < length; i++) {
    // If password length less than 9, all value random
    if (password.length < length - 4) {
      // Get random passwordArray index
      const arrayRandom = Math.floor(Math.random() * 4);
      // Get password array value
      const passwordItem = passwordArray[arrayRandom];
      // Get password array value random index
      // Get random real value
      const item = passwordItem[Math.floor(Math.random() * passwordItem.length)];
      password.push(item);
    } else {
      // If password large then 9, lastest 4 password will push in according to the random password index
      // Get the array values sequentially
      const newItem = passwordArray[n];
      const lastItem = newItem[Math.floor(Math.random() * newItem.length)];
      // Get array splice index
      const spliceIndex = Math.floor(Math.random() * password.length);
      password.splice(spliceIndex, 0, lastItem);
      n++;
    }
  }
  return password.join('');
};


/**
 * 获取当前年月
 */
export const dateChange = () => {
  const now = new Date();
  const year = String(now.getFullYear()); //年
  const month = now.getMonth() + 1; //月

  let clock = year;
  if (month < 10) {
    clock += '0';
  }

  clock += month;
  return clock;
};


// 校验只能输入数字
export const checkDigit = (data: any) => {
  const reg = /^\d+(?=\.{0,1}\d+$|$)/;
  if (data !== '') {
    if (!reg.test(data)) {
      // 返回，不往下执行
      return false;
    }
    return true;
  }
};
// export function debounce(fn: any) {
//   // eslint-disable-next-line no-undef
//   let timer: NodeJS.Timeout | null = null;
//   // eslint-disable-next-line no-undef
//   const firstClick = !timer;
//   if (firstClick) {
//     fn();
//   }
//   if (timer) {
//     clearTimeout(timer);
//   }
//   timer = setTimeout(() => {
//     timer = null;
//     if (!firstClick) {
//       fn();
//     }
//   }, 2000);
// }
// 判断数组内的元素是否完全相同
export const isAllEqual = (array: any) => {
  if (array.length > 0) {
    return !array.some(function (value: any) {
      return value !== array[0];
    });
  }
  return true;

};
// 比较日期大小 2021-02-06  2021-08-06
export const bjDate = (start: string, end: string) => {
  const date = new Date(start);
  const date3 = new Date(end);
  if (date.getTime() - date3.getTime() < 0) {
    return true;
  }
  return false;
};


/**
* Base64转换为二进制文件流(binary)
* @param {string} dataurl base64
*/
export const base64toFile = (dataurl: any, filename = 'file') => {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const suffix = mime.split('/')[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  const file = new File([u8arr], `${filename}.${suffix}`, {
    type: mime,
  });
  return file;
};


export const imageUrlToBase64 = (imageUrl: string) => {
  const image = new Image(); // 一定要设置为let，不然图片不显示
  image.setAttribute('crossOrigin', 'anonymous'); // 解决跨域问题
  image.src = `${imageUrl}`;
  return new Promise((resovle) => {
    image.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      const context: any = canvas.getContext('2d');
      context.drawImage(image, 0, 0, image.width, image.height);
      const quality = 0.8;
      const dataURL = canvas.toDataURL('image/jpeg', quality); // 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
      resovle(base64toFile(dataURL));
    };
  });
};


// 数组去重
export const duplicate = (arr: any) => {
  const newsArr: any = [];
  for (let i = 0; i < arr.length; i++) {
    if (newsArr.indexOf(arr[i]) === -1) {
      newsArr.push(arr[i]);
    }
  }
  return newsArr;
};

/**
* 把二进制文件保存到本地
*/
export function exportFile(file: { data: BlobPart; }) {
  const link = document.createElement('a');
  const blob = new Blob([file.data]);
  link.style.display = 'none';
  link.href = URL.createObjectURL(blob);
  link.download = '申请材料.docx';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}


export function timestampToTime(times: any[]) {
  // const time = times[1];
  let mdy = times[0];
  mdy = mdy.split('/');
  const month = parseInt(mdy[0]);
  const day = parseInt(mdy[1]);
  const year = parseInt(mdy[2]);
  return year + '-' + month + '-' + day;
}

export function phoneStar(tel: string) {
  if (tel) {
    const result = tel.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    return result;
  }
}
// 校验统一社会信用代码 返回值为true或false
export function isSocialCode(socialCode: string) {
  if (socialCode) {
    const reg = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;
    return reg.test(socialCode);
  }
}
// 校验手机号码
export function isPhone(value: any) {
  if (value) {
    const phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/;
    return phonereg.test(value);
  }
}
